/**
 * Copyright (c) 2018-2028.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sailmi.auth.granter;


import com.sailmi.common.constant.TokenConstant;
import com.sailmi.common.model.auth.AuthUser;
import com.sailmi.common.tool.utils.SecureUtil;
import com.sailmi.common.tool.utils.Func;
import com.sailmi.common.secure.user.IUserProvider;
import io.jsonwebtoken.Claims;

import org.springframework.stereotype.Component;

/**
 * RefreshTokenGranter
 *
 * @author yzh
 */
@Component

public class RefreshTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "refresh_token";

	private final IUserProvider userClient;

	public RefreshTokenGranter(IUserProvider userClient) {
		this.userClient = userClient;
	}

	/**
	 * {iss=issuser, aud=audience, iat=1691447465, tenant_id=000000,
	 * role_name=, user_code=8255326599655653376, user_id=, token_type=access_token,
	 * enterprise_id=000000, account=yinzhaohui, client_id=ATPWebClient_DESK,
	 * exp=1691807465, nbf=1691447465}
	 * @param tokenParameter 授权参数
	 * @return
	 */
	@Override
	public AuthUser grant(TokenParameter tokenParameter) {
		String tenantId = tokenParameter.getArgs().getStr("tenantId");
		String grantType = tokenParameter.getArgs().getStr("grantType");
		String refreshToken = tokenParameter.getArgs().getStr("refreshToken");
		AuthUser userInfo = null;
		if (Func.isNoneBlank(grantType, refreshToken) && grantType.equals(TokenConstant.REFRESH_TOKEN)) {
			System.out.println("111111111111"+refreshToken);
			Claims claims = SecureUtil.parseJWT(refreshToken);
			String userId = String.valueOf(claims.get(TokenConstant.USER_ID));
			System.out.println("111111111112"+claims  + "  userId:" + userId);
			userInfo = userClient.userInfo(Long.valueOf(userId));
		}
		System.out.println("111111111113"+userInfo.getUserId());
		return userInfo;
	}
}
